package com.gitee.flyzing.jxt;

import org.springframework.beans.BeanUtils;

import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

public class CommonUtil {

    public static boolean isNotNull(String str) {
        return str != null && !str.trim().equals("");
    }

    public static Object getPropertyValue(Object o, String propertyNames)  {
        Object propertyValue = null;
        String propertyName = "";
        if (propertyNames.indexOf(".") > -1) {
            propertyName = propertyNames.substring(0, propertyNames.indexOf("."));
            propertyNames = propertyNames.substring(propertyNames.indexOf(".") + 1);
        } else {
            propertyName = propertyNames;
            propertyNames = "";
        }

        try {
            if (o instanceof Map) {
                propertyValue = ((Map<?, ?>) o).get(propertyName);
            } else {
                PropertyDescriptor property = BeanUtils.getPropertyDescriptor(o.getClass(), propertyName);
                if (property != null) {
                    propertyValue = property.getReadMethod().invoke(o, new Object[]{});
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (propertyValue != null && isNotNull(propertyNames)) {
            return getPropertyValue(propertyValue, propertyNames);
        } else {
            return propertyValue;
        }
    }
}
